import { type CveItem } from "~/server/api/routers/vulnerability";
import { cn } from "~/components/lib/utils";

export const ThreatBar = ({ cve }: { cve: CveItem }) => {
  const summary = threatSummary(cve);
  return (
    <div className="w-full rounded-md border border-gray-200 bg-white dark:border-gray-700 dark:bg-gray-800">
      <div className="grid grid-cols-1 gap-4 p-4 md:grid-cols-4">
        {/* Attack Vector */}
        <div className="flex flex-col">
          <div className="pb-1 text-xs font-medium uppercase text-gray-500 dark:text-gray-400">
            Attack Vector
          </div>
          <div className="text-gray-900 dark:text-white">
            {cve.metrics?.cvssMetricV31?.[0]?.cvssData?.attackVector || "N/A"}
          </div>
        </div>

        {/* Attack Complexity */}
        <div className="flex flex-col">
          <div className="pb-1 text-xs font-medium uppercase text-gray-500 dark:text-gray-400">
            Attack Complexity
          </div>
          <div className="text-gray-900 dark:text-white">
            {cve.metrics?.cvssMetricV31?.[0]?.cvssData?.attackComplexity ||
              "N/A"}
          </div>
        </div>

        {/* Privileges Required */}
        <div className="flex flex-col">
          <div className="pb-1 text-xs font-medium uppercase text-gray-500 dark:text-gray-400">
            Privileges Required
          </div>
          <div className="text-gray-900 dark:text-white">
            {cve.metrics?.cvssMetricV31?.[0]?.cvssData?.privilegesRequired ||
              "N/A"}
          </div>
        </div>

        {/* User Interaction */}
        <div className="flex flex-col">
          <div className="pb-1 text-xs font-medium uppercase text-gray-500 dark:text-gray-400">
            User Interaction
          </div>
          <div className="text-gray-900 dark:text-white">
            {cve.metrics?.cvssMetricV31?.[0]?.cvssData?.userInteraction ||
              "N/A"}
          </div>
        </div>
      </div>

      {/* Summary section */}
      {summary.length > 1 && (
        <div className="border-t border-gray-200 p-4 dark:border-gray-700">
          <div className="flex items-start gap-3">
            <svg
              xmlns="http://www.w3.org/2000/svg"
              fill="none"
              viewBox="0 0 24 24"
              strokeWidth="1.5"
              stroke="currentColor"
              className="h-5 w-5 flex-shrink-0 text-amber-500 dark:text-amber-400"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                d="M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126zM12 15.75h.007v.008H12v-.008z"
              />
            </svg>
            <div className="text-sm text-gray-700 dark:text-gray-300">
              {summary.map((line, index) => (
                <span key={index}>{line}</span>
              ))}
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

// Dashboard version of ThreatBar that accepts count and critical props
export interface DashboardThreatBarProps {
  count: number;
  critical: number;
}

export const DashboardThreatBar: React.FC<DashboardThreatBarProps> = ({
  count,
  critical,
}) => {
  return (
    <div className="mt-2 flex flex-col">
      <div className="flex justify-between text-xs text-gray-500">
        <span>Vulnerabilities</span>
        <span>{count} total</span>
      </div>
      <div className="mt-1 h-2 w-full overflow-hidden rounded-full bg-gray-200">
        <div
          className="h-full bg-red-500"
          style={{ width: `${Math.min((critical / count) * 100, 100)}%` }}
        />
      </div>
      {critical > 0 && (
        <div className="mt-1 text-xs text-red-500">
          {critical} critical issue{critical !== 1 ? "s" : ""}
        </div>
      )}
    </div>
  );
};

//Threat Summary Builder
// * Salutation -> number of factors yields increased risk

const threatSummary = (cve: CveItem) => {
  const summary = [];
  summary.push("");

  if (cve.cisaExploitAdd) {
    summary.push(
      `An entry exists in the CISA Known Exploited Vulnerabilities catalog for this condition. `
    );
  }

  // * CVSS Factors -> Read from vector string
  // Parse vector string
  let AV, AC, PR, UI;

  if (cve.metrics?.cvssMetricV31?.[0]?.cvssData) {
    const vector =
      cve.metrics?.cvssMetricV31?.[0]?.cvssData.vectorString.split("/");
    AV = vector[0]?.split(":")[1];
    AC = vector[1]?.split(":")[1];
    PR = vector[2]?.split(":")[1];
    UI = vector[3]?.split(":")[1];
  }

  // * Attack Vector
  if (AV === "N") {
    summary.push(`This vulnerability is remotely exploitable. `);
  } else if (AV === "A") {
    summary.push(
      `This vulnerability is remotely exploitable from an adjacent network. `
    );
  } else if (AV === "L") {
    summary.push(`This vulnerability is locally exploitable. `);
  } else if (AV === "P") {
    summary.push(
      `This vulnerability is only exploitable by a physical attacker. `
    );
  }
  // * Attack Complexity
  if (AC === "L") {
    summary.push(`This vulnerability is trivial for an attacker to exploit. `);
  } else if (AC === "H") {
    summary.push(`Exploitation of this vulnerability may prove challenging. `);
  }
  // * Privileges Required
  if (PR === "N") {
    summary.push(
      `This vulnerability does not require any special privileges to exploit. `
    );
  } else if (PR === "L") {
    summary.push(`Only low level access is required. `);
  } else if (PR === "H") {
    summary.push(
      `An elevated level of access is required to exploit this issue. `
    );
  }
  // * User Interaction
  if (UI === "N") {
    summary.push(`No user interaction is necessary. `);
  } else if (UI === "R") {
    summary.push(
      `A user must interact with the system to trigger the exploit payload. `
    );
  }

  return summary;
};
